from androidSta.common import *
from time import sleep
#################################################################################################
#################################################################################################
def android_get_ScreenState(devicesid=None):
    ''' *函数说明*: 查看屏幕状态（解锁|锁定）

        *参数说明*:
            devicesid  设备序列号     ...可选
        *example*:
            android_get_ScreenState    c08c1b39
            screenState=2为开启   screenState=0关 (屏幕唤醒)
            mDreamingLockscreen=false(true)（解锁|锁定）
        *返回值*:
            1为解锁
            2位锁定
    '''
    ret = ''
    ret = android_send_adbshell('adb shell dumpsys window policy', devicesid)
    if 'mDreamingLockscreen=false' in ret:
        logger.info("The screen is unlocked")
        return 1
    elif 'mDreamingLockscreen=true' in ret:
        logger.info("The screen is locked")
        return 2
    else:
        logger.info("The screen information is {}".format(ret))
        raise Exception('The mDreamingLockscreen is not find')

#################################################################################################
#################################################################################################
def android_Unlock_screen(devicesid=None):
    ''' *函数说明*: 解锁屏幕
        adb shell input swipe 500 1000 500 500 500
        *参数说明*:
            devicesid  设备序列号     ...可选
        *example*:
            android_get_ScreenState    c08c1b39
            screenState=2为开启   screenState=0关 (屏幕唤醒)
            mDreamingLockscreen=false(true)（解锁|锁定）
    '''
    ret = android_get_ScreenState(devicesid)
    if ret == 1:
        return 'The screen Unlock success'
    else:
        for i in range(5):
            #先点亮屏幕
            android_input_KEYCODE(26,devicesid)
            android_input_swipe(500 , 1000 , 500 , 500,devicesid)
            sleep(2)
            ret = android_get_ScreenState(devicesid)
            if ret == 1:
                return 'The screen Unlock success'

#################################################################################################
#################################################################################################
def android_get_ipv4(argv,devicesid=None):
    ''' *函数说明*: 获取安卓手机的无线IP地址
        adb shell ifconfig wlan0
        *参数说明*:
            devicesid  设备序列号     ...可选
            flags      是否要求获取IP地址(true/false), 类型: str, 可选
        *example*:
            android_get_ipv4    --intf wlan0
    '''
    ret = ''
    intf = 'wlan0'
    flags = 'true'
    cmd = argv.strip().split()
    i = 0
    while i < len(cmd):
        tmpOpt = cmd[i]
        if tmpOpt == '--intf':
            i+=1
            intf = cmd[i]
        elif tmpOpt == '--FLAG':
            i+=1
            flags = cmd[i]
        i+=1

    ret = android_send_adbshell('adb shell ifconfig {}'.format(intf),devicesid)
    result = re.search('\d+\.\d+\.\d+\.\d+', ret)
    if not result:
        for i in range(18):
            time.sleep(2)
            ret = android_send_adbshell('adb shell ifconfig {}'.format(intf),devicesid)
            result = re.search('\d+\.\d+\.\d+\.\d+', ret)
            if result:
                break
    if result and flags == 'true':
        return result.group(0)
    elif not result and  flags != 'true':
        return True
    else:
        return ""

#################################################################################################
#################################################################################################
def android_ping_addr(argv, devicesid=None):
    ''' *函数说明*: ping 指定 地址

        *参数说明*:
            --dst_addr:     指定ping包的目的地址, 必选
            --count:        指定Ping包个数, 可选
            --size:         指定ping包大小, 可选
            --mode:         限定ping包的结果类型, 可选值有1,2,3,4, 默认值为1
                mode=1:     只要有一个ping报文可达, 通过
                mode=2:     所有报文都可达, 通过
                mode=3:     ping不通时，通过
                mode=4:     只管执行ping操作, 不关心结果

        *命令说明*:

        *example*:
            android_ping_addr  --dst_addr www.baidu.com --count 4 --mode 2
 
        *返回值*:  回显内容

    '''

    dst_addr = ""
    count = ""
    mode = 2
    size = ''

    cmd = argv.strip().split()
    i = 0
    while i < len(cmd):
        tmpOpt = cmd[i]
        if tmpOpt == '--dst_addr':
            i+=1
            dst_addr = cmd[i]
        if tmpOpt == '--count':
            i+=1
            count = '-c ' + cmd[i]       
        if tmpOpt == '--size':
            i+=1
            size = '-s ' + cmd[i]
        if tmpOpt == '--mode':
            i+=1
            mode = cmd[i]    
        i+=1
    ret = ''
    ret = android_send_adbshell('adb shell ping {} {} {}'.format(count, size, dst_addr),devicesid)
    logger.info(ret)
    a = re.findall('(\d+)% packet loss',ret)
    if a:      
        if int(mode) == 1:
            if int(a[0]) < 100:
                return ret
            else:
                raise Exception('ping {} fail'.format(dst_addr))
        elif int(mode) == 2:
            if int(a[0]) == 0:
                return ret
            else:
                raise Exception('ping {} fail'.format(dst_addr))
        elif int(mode) == 3:
            if int(a[0]) == 100:
                return ret
            else:
                raise Exception('ping {} fail'.format(dst_addr))
        elif int(mode) == 4:
                return ret
    elif 'unknown host' in ret and int(mode) == 3:
        return ret
    elif 'unknown host' in ret and int(mode) == 4:
        return ret
    else:
        raise Exception('ping {} fail'.format(dst_addr))

#################################################################################################
#################################################################################################
def android_connect_AP(argv, devicesid_index=0):
    ''' *函数说明*: 安卓关联SSID
        *参数说明*:
            --encryptype:     加密类型, 必选
            --ssid:           SSID, 必选
            --key:            密码, 可选
            devicesid_index   连接pc安卓设备序列号索引
        *example*:
            手机关联SSID   ssid=${ssid5}   Encryption_mode=psk  key=${password}   devicesid_index=0
            android_connect_AP     --encryptype open --ssid ${ssid5} --key ${password}   ${devicesid_index}
        *返回值*:
            回显内容
    '''

    encryptype = ""
    ssid = ""
    key = ""

    cmd = argv.strip().split()
    i = 0
    while i < len(cmd):
        tmpOpt = cmd[i]
        if tmpOpt == '--encryptype':
            i += 1
            encryptype = cmd[i]
        if tmpOpt == '--ssid':
            i += 1
            ssid = cmd[i]
        if tmpOpt == '--key':
            i += 1
            key = cmd[i]
        i += 1

    devicesid = __input_ssidInterface(devicesid_index)
    if encryptype == 'open':
        logger.info(u'点击网络名称输入框')
        android_input_tap(600, 320, devicesid)      #点击网络名称输入框
        logger.info(u'输入SSID')
        android_input_text(ssid, devicesid)                  #输入SSID
        logger.info(u'点击√')
        android_input_tap(1000, 140, devicesid)      #点击√
        sleep(8)
        logger.info(u'点击home')
        android_input_KEYCODE(3, devicesid)         #点击home
    elif encryptype == 'psk':
        logger.info(u'点击网络名称输入框')
        android_input_tap(600, 320, devicesid)       #点击网络名称输入框
        logger.info(u'输入SSID')
        android_input_text(ssid, devicesid)                  #输入SSID
        logger.info(u'点击加密方式选择')
        android_input_tap(500, 600, devicesid)       #点击加密方式选择
        logger.info(u'点击WPA/WPA2 PSK')
        android_input_tap(500, 1666, devicesid)   #点击WPA/WPA2 PSK
        logger.info(u'点击密码')
        android_input_tap(500, 780, devicesid)    #点击密码
        logger.info(u'输入密码')
        android_input_text(key, devicesid)               #输入密码
        logger.info(u'点击√')
        android_input_tap(1000, 140, devicesid) 
        sleep(8)          #点击√
        logger.info(u'点击home')
        android_input_KEYCODE(3, devicesid)               #点击home
    else:
        raise Exception('connect %s fail' % ssid)
    ret = __checkconnect(ssid, devicesid)
    android_input_KEYCODE(3, devicesid)               #点击home
    if 'successful' in ret:
        return ret
    else:
        raise Exception('connect %s fail' % ssid)


def __input_ssidInterface(devicesid_index=0):
    ''' *函数说明*: 进入输入SSID界面
    '''
    devicesid = android_get_devices(devicesid_index)
    #android_Unlock_screen(devicesid)   #解锁屏幕
    android_input_KEYCODE(3, devicesid)     #点击home

    # android_get_uidumpxml(devicesid)  
    # x,y = android_get_coordinate(u'设置')
    # y -= 100  #主桌面显示APP的文字描述位置向上移动至图标
    # android_input_tap(x, y ,devicesid) 
    logger.info(u'点击设置')
    android_input_tap(913, 1355 ,devicesid) 
    sleep(1)

    android_input_swipe(500, 1000, 500, 10000, devicesid)  #防止页面没有置顶
    sleep(1)
    # android_get_uidumpxml(devicesid) 
    # x,y = android_get_coordinate('WLAN')  
    # android_input_tap(x, y ,devicesid)
    logger.info(u'点击WLAN')
    android_input_tap(272, 853 ,devicesid)
    sleep(3)

    android_get_uidumpxml(devicesid) 
    WLANx,WLANy = android_get_coordinate(u'开启WLAN')  
    if android_get_coordinate(u'要查看可用网络，请打开 WLAN。'):#判断WLAN是否开启
        android_input_tap(WLANx, WLANy, devicesid) 
        sleep(5)
    sleep(3)
    android_input_swipe(500, 1000, 500, -10000, devicesid) #拉到最底部
    sleep(2)
    android_input_swipe(500, 1000, 500, -10000, devicesid) #拉到最底部
    android_input_tap(600, 1400 ,devicesid)    #快速点击其他...
    sleep(1)
    return devicesid

def __checkconnect(ssid, devicesid):
    ''' *函数说明*: 判断是否关联到指定SSID
    '''
    android_input_KEYCODE(3, devicesid)               #点击home
    sleep(2)
    android_input_KEYCODE(3, devicesid)               #点击home
    
    # android_get_uidumpxml(devicesid)  
    # x,y = android_get_coordinate(u'设置')
    # y -= 100  #主桌面显示APP的文字描述位置向上移动至图标
    # android_input_tap(x, y ,devicesid) 
    logger.info(u'点击设置')
    android_input_tap(913, 1355 ,devicesid) 
    sleep(1)
    android_input_swipe(500, 1000, 500, 10000, devicesid)  #防止页面没有置顶
    android_get_uidumpxml(devicesid)
    try:
        x,y = android_get_coordinate('{}'.format(ssid))
    except:
        x = None  
    if x:
        return 'connect %s successful' % ssid
    else:
        return 'connect %s fail' % ssid
    # for i in range(2):
    #     android_get_uidumpxml(devicesid)
    #     try:
    #         x,y = android_get_coordinate('{}'.format(ssid))
    #     except:
    #         x = None  
    #     if x:
    #         return 'connect %s successful' % ssid
    #     sleep(2)
    # return 'connect %s fail' % ssid